package com.study.springbootsecurity.service.impl;

import com.study.springbootsecurity.entity.LoginUser;
import com.study.springbootsecurity.entity.Role;
import com.study.springbootsecurity.entity.SysUser;
import com.study.springbootsecurity.exception.BusinessException;
import com.study.springbootsecurity.mapper.SysUserMapper;
import com.study.springbootsecurity.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description: TODO
 * @author: Huangjianyun
 * @date: 2025-06-05 16:39
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    // 基于set方法注入
    SysUserService sysUserService;

    @Autowired
    public void setSysUserService(SysUserService sysUserService) {
        this.sysUserService = sysUserService;
    }


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = sysUserService.getByUsername(username);
        if (ObjectUtils.isEmpty(sysUser)) {
            throw new BusinessException("UserDetailsServiceImpl类loadUserByUsername的sysUser查询为null~~~~~");
        }
        List<Role> roles = sysUser.getRoles();
        List<String> grantedAuthorities = new ArrayList<>();
        for (Role role : roles) {
            // 封装用户所拥有所有角色权限到List<String>列表
            grantedAuthorities.addAll(role.getPermissions());
        }
        return new LoginUser(sysUser,grantedAuthorities);
    }
}
